<template>
  <div class="content-table">
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div>
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-row>
              <el-col :span="3">
                <el-form-item label="姓名" prop="nameLike">
                  <el-input
                    class="search-input"
                    v-model.trim="formInline.nameLike"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="所在单位部门" prop="companyNameLike">
                  <el-input
                    class="search-input"
                    v-model.trim="formInline.companyNameLike"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="科技人才类别" prop="kcMemberName">
                  <el-select
                    class="search-input"
                    v-model="formInline.kcMemberName"
                    filterable
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      label="基础研究人员"
                      value="基础研究人员"
                    ></el-option>
                    <el-option
                      label="科技研发人员-科研项目管理人员"
                      value="科技研发人员-科研项目管理人员"
                    ></el-option>
                    <el-option
                      label="科技研发人员-研究和技术人员"
                      value="科技研发人员-研究和技术人员"
                    ></el-option>
                    <el-option
                      label="科技管理人员"
                      value="科技管理人员"
                    ></el-option>
                    <el-option
                      label="科技直接服务人员"
                      value="科技直接服务人员"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="职务/职位" prop="position">
                  <el-input
                    class="search-input"
                    v-model.trim="formInline.position"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="更新时间" prop="updateTime">
                  <el-date-picker
                    style="width: 90%"
                    v-model.trim="formInline.updateTime"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item class="right-position">
                  <el-button type="primary" @click="handleSearch">
                    搜索
                  </el-button>
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div>
            <el-button
              type="primary"
              @click="handleOpen"
              class="add-option"
              v-auth="`/expert/science--add`"
              >添加</el-button
            >
            <el-button
              type="primary"
              @click="exportExcel"
              class="add-option"
              v-auth="`/expert/science--export`"
              >导出</el-button
            >
            <importExcel
              fileName="科技人员导入模板.xlsx"
              :actionUrl="importUrl"
              name="uploadFile"
              auth="/expert/science--import"
              @onSuccess="handleSearch"
            />
          </div>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="state.tableData"
            border
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column type="index" label="序号" width="60">
              <template v-slot="scope">
                <span>{{
                  (formInline.pageNum - 1) * formInline.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="110"
            ></el-table-column>
            <el-table-column
              prop="companyName"
              label="所在单位部门"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="kcMemberName"
              label="科技人才类别"
              min-width="160"
            ></el-table-column>
            <el-table-column
              prop="honorTitle"
              label="荣誉称号"
              show-overflow-tooltip
              min-width="120"
            ></el-table-column>

            <el-table-column
              prop="position"
              label="职务/职位"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="email"
              label="邮箱"
              min-width="160"
            ></el-table-column>
            <el-table-column
              prop="lastUpdateTime"
              label="登记时间"
              min-width="120"
            >
              <template v-slot="scope">
                {{ scope.row.lastUpdateTime ? scope.row.lastUpdateTime.split(" ")[0] : '' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="text"
                  @click="handleCheckDetail(row)"
                  v-auth="`/expert/science--look`"
                  >查看</el-button
                >
                <el-button
                  type="text"
                  @click="handleEdit(row, true)"
                  v-auth="`/expert/science--edit`"
                  >编辑</el-button
                >
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button
                      :disabled="row.isEmp === '1'"
                      type="text"
                      v-auth="`/expert/science--delete`"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-dialog
      :title="mode === 'add' ? '添加科技人员' : '编辑科技人员'"
      v-model="dialogFormVisible"
      destroy-on-close
      width="700px"
    >
      <user-detail
        @emitClose="emitClose"
        :mode="mode"
        :userInfo="state.userInfo"
        :companyInfo="state.companyInfo"
      />
    </el-dialog>
    <el-dialog
      v-model="state.detailVisible"
      destroy-on-close
      title="登记历史记录"
      width="80%"
    >
      <check-detail :userInfo="state.userInfo" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import moment from "moment";
import { reactive, ref } from "vue";
import UserDetail from "./components/UserDetail.vue";
import CheckDetail from "./components/checkDetail.vue";
import { deleteUser } from "/@/api/user";
import importExcel from "/@/components/importExcel/index.vue";
import NotifMessage from "/@/utils/message/notification";

import axios from "axios";
import { cloneDeep } from "lodash-es";
import { ModeType, UserInfoType } from "./types";
import { postDictList } from "/@/api/common";
import { getScienceList } from "/@/api/expert";
import { roleList } from "/@/api/roles";
import { storageLocal } from "/@/utils/storage";
const baseUrl = import.meta.env.VITE_BASE_URL;
const formRef = ref<HTMLFormElement | null>(null) as any;

let loading = ref<boolean>(false);
let mode = ref<ModeType>("add");
let dialogFormVisible = ref<boolean>(false);
let total = ref<number>(0);
let formInline = reactive<any>({
  nameLike: "",
  userNameLike: "",
  companyNameLike: "",
  position: "",
  kcMemberName: "",
  kcRoleCode: "",
  updateTime: "",
  pageNum: 1,
  pageSize: 10
});

let state = reactive({
  tableData: [] as UserInfoType[],
  userInfo: {} as UserInfoType,
  companyInfo: {},
  detailVisible: false // 查看详情弹窗状态
});
const importUrl = ref(
  import.meta.env.VITE_BASE_URL + "/rdms-admin/scienceMember/import"
);

let userTypeList = ref([]);

let userRoleList = ref([]);

// 请求表格数据
async function getTableData(obj: object = {}) {
  // 真实请求待添加
  loading.value = true;
  try {
    let copyParams = cloneDeep(obj);
    const { code, data } = await getScienceList(copyParams);
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

const exportExcel = async () => {
  let downloadUrl = `/rdms-admin/scienceMember/export`;
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }
  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/rdms-admin/scienceMember/export`;
  }
  if (formInline.updateTime) {
    formInline.updateTime = moment(formInline.updateTime).format("YYYY-MM-DD");
  } else {
    formInline.updateTime = "";
  }
  const param = Object.assign({}, formInline, { pageSize: 0, pageNum: 1 });
  axios({
    method: "post",
    url: downloadUrl,
    data: param,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  }).then(res => {
    const data = res.data;
    // @ts-ignore
    const url = window.URL.createObjectURL(new Blob([data]));
    const a = document.createElement("a");
    a.style.display = "none";
    a.href = url;
    // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
    a.setAttribute("download", `科技人员.xlsx`);
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(a.href);
    document.body.removeChild(a);
  });
};
// 打开添加人员弹窗
const handleOpen = (): void => {
  dialogFormVisible.value = true;
  mode.value = "add";
  // console.log(activeCategory);
  // if (activeCategory.value.id) {
  // state.companyInfo = activeCategory;
  // }
};

const emitClose = (isSubmit: boolean) => {
  dialogFormVisible.value = false;
  if (isSubmit) {
    formInline.pageNum = 1;
    getTableData(formInline);
  }
};

// 重置条件
const handleReset = (): void => {
  formRef.value.resetFields();
};

// 根据条件进行搜索
const handleSearch = (): void => {
  const params = cloneDeep(formInline);
  if (formInline.updateTime) {
    params.updateTime = moment(formInline.updateTime).format("YYYY-MM-DD");
  } else {
    params.updateTime = "";
  }
  getTableData(params);
};

// 编辑用户
const handleEdit = (row, isEdit): void => {
  dialogFormVisible.value = true;
  mode.value = isEdit ? "edit" : "view";
  state.userInfo = row;
};

// 查看详情弹窗状态
const handleCheckDetail = row => {
  state.detailVisible = true;
  state.userInfo = row;
};

// 删除用户
const handleDelete = async (item: any) => {
  try {
    const { code, message } = await deleteUser({ id: item.id });
    if (code === 200) {
      // successMessage(`${message}`);
      NotifMessage.success(message);
      getTableData(formInline);
    } else {
      // warnMessage(`${message}`);
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 人员类型
const initUserTypeList = async () => {
  try {
    const params = {
      dicType: "rd_user_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      userTypeList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 人员角色
const initUserRoleList = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 0
    };
    const { code, data } = await roleList(params);
    if (code === 200) {
      userRoleList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

// 请求数据
getTableData(formInline);
initUserTypeList();
initUserRoleList();
</script>
<style>
.el-popper {
  max-width: 500px;
  line-height: 1.5;
}
</style>
<style lang="scss" scoped></style>
